package br.ufrn.engcomp.arq.dao;

/**
 * @author Claudio
 *
 */

import java.util.ArrayList;
import java.util.List; 

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import br.ufrn.engcomp.arq.dao.IGenericDAO;
import br.ufrn.engcomp.arq.dominio.Entidade;
import br.ufrn.engcomp.arq.exceptions.DAOException;




public class GenericDAO<E extends Entidade> implements IGenericDAO<E> {
	private static EntityManagerFactory emf; 
	
	protected EntityManager getEntityManager() {
		return emf.createEntityManager();
	}
	
	public GenericDAO () {
		emf = Persistence.createEntityManagerFactory("academia");
	}
		
	public boolean create(E model) throws DAOException{ 
		EntityManager em = getEntityManager();
		boolean retorno = false;
		try {
			em.getTransaction().begin();
			em.persist(model);
			em.getTransaction().commit();
			retorno = true;
		} catch (Exception ex) {
			em.getTransaction().rollback();
			throw new DAOException(ex);
		} finally{
			em.close();
		}
		return retorno;
	} 
	
	public boolean update(E model) throws DAOException{ 
		EntityManager em = getEntityManager();
		boolean retorno = false;
		try {
			em.getTransaction().begin();
			em.merge(model);
			em.getTransaction().commit();
			retorno = true;
		} catch (Exception ex) {
			em.getTransaction().rollback();
			throw new DAOException(ex);
		} finally{
			em.close();
		}
		return retorno; 
	} 
	
	public boolean delete(E model) throws DAOException { 
		EntityManager em = getEntityManager();
		boolean retorno = false;
		try {
			em.getTransaction().begin();
			model = em.merge(model);
			em.remove(model);
			em.getTransaction().commit();
			retorno = true;
		} catch (Exception ex) {
			em.getTransaction().rollback();
			throw new DAOException(ex);
		} finally{
			em.close();
		}
		return retorno;
	} 
	
	@SuppressWarnings("unchecked") 
	public List<E> findAll(E model) throws DAOException{ 
		EntityManager em = getEntityManager();
		List<E> retorno = new ArrayList<E>();
		try {
			Query q = em.createQuery("select object(model) from "+ model.getClassName() + " as model");
			retorno = q.getResultList();
		} catch (Exception ex) {
			throw new DAOException(ex);
		} finally{
			em.close();
		}
		return retorno;
	} 
	
	
}
